import { isUrl } from '~/server/validation';
import { formatDateByNow } from '~/utils/util.date';
import { AdminUserModel } from '~/server/models/admin_user.model';

/**
 * @api {patch} /admin/user/update 管理员用户修改资料
 * @apiName 管理员用户修改资料
 * @apiGroup 后台管理员用户
 * @apiDescription 管理员用户修改资料，需携带 Token 进行验证
 *
 * @apiPermission all admin user
 *
 * @apiSampleRequest /admin/user/update
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiBody {String} avatar 头像
 * @apiBody {String} nickname 昵称
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '更新成功',
 * }
 */
export default defineEventHandler(async (event) => {
	const { user } = event.context;

	try {
		const { avatar, nickname } = await readBody(event);

		if (!isUrl(avatar) || typeof nickname !== 'string' || nickname.length < 1) {
			return {
				code: 0,
				message: '参数错误',
			};
		}

		await AdminUserModel.findOneAndUpdate(
			{ id: user._id },
			{ $set: { avatar, nickname, updatedAt: formatDateByNow() } }
		);

		return {
			code: 1,
			message: '更新成功',
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
